﻿#include "threadforloading.h"
#include <QCoreApplication>
#include <QDebug>
#include <QDir>

namespace HttpLoading {

HttpTask::HttpTask(QJsonObject allvalue){
    m_all = allvalue;
}

HttpTask::~HttpTask()
{

}

void HttpTask::run()
{
    //    QSharedPointer<Http> process(new Http(nullptr,m_all));
    //    connect(process.data(), &Http::someData,[&](){
    //        emit someData(process->readNowStatus());
    //    });
    //    process->startDownLoad();
    //    QElapsedTimer elapTime;
    //    elapTime.start();
    //    while(!process->isFinished()&&elapTime.elapsed()<5*1000){
    //        QCoreApplication::processEvents();
    //    }
//    qDebug()<<m_all;
    QString cmdPath = QCoreApplication::applicationDirPath()+"/thirdpart/aria2c.exe";
    QFileInfo file(cmdPath);
    if(!file.exists()){
        qDebug()<<QStringLiteral("缺少aria2c工具,请检查安装包!");
        m_all.insert("curl",0);
        m_all.insert("statusValue","");
        m_all.insert("status",QStringLiteral("缺少aria2c工具,请检查安装包!"));
        emit someData(m_all);
        return;
    }
    QString filePath = m_all.value("filePath").toString().right(m_all.value("filePath").toString().length()-8);
    file = filePath;
    if(!file.exists()){
        QDir dir;
        if(!dir.mkpath(filePath)){
            QString error = QStringLiteral("创建路径失败:")+filePath;
            qDebug()<<error;
            m_all.insert("curl",0);
            m_all.insert("statusValue","");
            m_all.insert("status",error);
            emit someData(m_all);
            return;
        }
    }
    QSharedPointer<QProcess> process(new QProcess);
    connect(process.data(), &QProcess::readyReadStandardOutput,[&](){
        QByteArray answer = process->readAllStandardOutput();
//        qDebug().noquote()<<answer;
        if(answer.contains("[ERROR]")){
            m_all.insert("curl",1);
            m_all.insert("statusValue","");
            m_all.insert("status",QString::fromUtf8(answer.mid(answer.indexOf("[ERROR]"),answer.indexOf("\n\n")-answer.indexOf("[ERROR]"))));
            emit someData(m_all);
        }
        else if(answer.contains("Download Results")&&answer.contains("Status Legend")){
            QString result = QString::fromUtf8(answer.mid(answer.indexOf("Download Results"),answer.indexOf("Status Legend")-answer.indexOf("Download Results")));
            result = result.simplified();
            QFileInfo file(result.split("|").last());
            if(m_all.value("fileName").toString()!=file.fileName()){
                qDebug()<<"File already exists. Renamed to:"<<file.fileName();
                m_all.insert("Renamed",file.fileName());
            }
        }

        if(answer.contains("[#")&&answer.contains("]")){
            QString strTemp = QString::fromUtf8(answer.mid(answer.indexOf("[#"),answer.indexOf("]")-answer.indexOf("[#"))).replace("[","").replace("]","");
            QStringList temp = strTemp.split(" ");
            temp.removeFirst();
            temp.insert(0,temp.value(0).mid(temp.value(0).indexOf("(")+1).replace(")",""));
            m_all.insert("curl",2);
            m_all.insert("status",temp.join("|"));
            emit someData(m_all);
        }

        if(answer.contains("Status Legend:")){
            answer = answer.mid(answer.indexOf("Status Legend:"));
            m_all.insert("curl",1);
            if(answer.contains("OK")){
                m_all.insert("statusValue","100%");
                m_all.insert("status","100%");
            }
            else{
                m_all.insert("statusValue","");
                m_all.insert("status",QString::fromUtf8(answer.mid(answer.indexOf("(")).replace("\n","")));
            }
        }
    });
    connect(process.data(), &QProcess::readyReadStandardError, [&](){
        QByteArray answer = process->readAllStandardError();
//        qDebug().noquote()<<answer;
        m_all.insert("curl",0);
        m_all.insert("statusValue","");
        m_all.insert("status",QString::fromUtf8(answer));
        emit someData(m_all);
    });
    QStringList args;
    args.append("-o");
    args.append(m_all.value("fileName").toString());
    args.append(QString("--dir=%1").arg(filePath.replace("\\","\\\\")));
    args.append(m_all.value("fileHttp").toString());

    process->start(cmdPath,args);
    process->waitForFinished();
    m_all.insert("curl",0);
    emit someData(m_all);
    qDebug()<<"http down finished";
}

Controller::Controller() {
    pool = new QThreadPool;
    pool->setMaxThreadCount(3);
}

void Controller::addNewTask(QJsonObject value)
{
    HttpTask *ptr = new HttpTask(value);
    connect(ptr,SIGNAL(someData(QJsonObject)),this,SLOT(someData(QJsonObject)));
    pool->start(ptr);
}

void Controller::someData(QJsonObject value)
{
    emit getReturn(value);
}
}
